﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using CRMAdminDashboard.Properties;
using System.Web.Services.Protocols;

namespace CRMAdminDashboard
{
    public partial class FormLogin : Form
    {

        #region Constants

        private const string SETTING_CRMURL = "CrmUrl";
        private const string SETTING_CRMORG = "CrmOrganization";
        private const string SETTING_DOMAIN = "Domain";
        private const string SETTING_USERID = "UserId";
        private const string SETTING_AUTHMODE = "AuthenticationMode";
        private const string SETTING_UTILITY = "Utility";

        #endregion

        #region Properties

        public string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != string.Empty)
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        public string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        #endregion

        #region Fields

        /// <summary>
        /// Static pointer to my console
        /// </summary>
        private static TextBox _logWindow;

        /// <summary>
        /// Code behind
        /// </summary>
        private HelperLogin _helper;

        /// <summary>
        /// The utility that is currently running
        /// </summary>
        private IUtilityForm _utilityForm;

        #endregion

        #region Entry Points

        /// <summary>
        /// Standard constructor
        /// </summary>
        public FormLogin()
        {
            InitializeComponent();
            _logWindow = txtBoxConsole;
        }

        /// <summary>
        /// Called by the uility form when closed
        /// </summary>
        public void ForceLogout()
        {
            btnLogout_Click(this, null);
        }

        /// <summary>
        /// Write on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(string msg)
        {
            _logWindow.AppendText(msg);
        }

        /// <summary>
        /// Write an exception on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(Exception ex)
        {
            ClearLog();
            WriteLog(FormatException(ex) + Environment.NewLine + Environment.NewLine);
        }

        /// <summary>
        /// Clear the console
        /// </summary>
        public static void ClearLog()
        {
            _logWindow.Clear();
        }

        /// <summary>
        /// Some rudimentary formatting of exception useful before logging.
        /// </summary>
        public static string FormatException(Exception ex)
        {
            if (ex is SoapException)
            {
                SoapException sex = (SoapException)ex;
                if (sex.Detail != null && sex.Detail.InnerText != null)
                {
                    return sex.Detail.InnerText;
                }
            }
            return ex.ToString();
        }

        #endregion

        #region Local Methods

        /// <summary>
        /// Enable/disable controls accordingly
        /// </summary>
        private void EnableControls()
        {
            if (_helper == null)
            {
                if (cbAuthMode.SelectedIndex == 2)
                {
                    // if LIVE, Url and Domain are not relevant
                    txtBoxUrl.Enabled = false;
                    txtBoxDomain.Enabled = false;
                }
                else
                {
                    txtBoxUrl.Enabled = true;
                    txtBoxDomain.Enabled = true;
                }
                txtBoxOrganization.Enabled = true;
                txtBoxUserId.Enabled = true;
                txtBoxPassword.Enabled = true;
                cbAuthMode.Enabled = true;
                cbUtility.Enabled = true;

                btnLogin.Enabled = true;
                btnLogout.Enabled = false;
            }
            else
            {
                txtBoxUrl.Enabled = false;
                txtBoxOrganization.Enabled = false;
                txtBoxDomain.Enabled = false;
                txtBoxUserId.Enabled = false;
                txtBoxPassword.Enabled = false;
                cbAuthMode.Enabled = false;
                cbUtility.Enabled = false;

                btnLogin.Enabled = false;
                btnLogout.Enabled = true;
            }
        }

        /// <summary>
        /// Guess the organization if the Auth mode is IFD
        /// </summary>
        private void SetOrganization()
        {
            // if IFD we strip the organization from the url
            string url = txtBoxUrl.Text;
            if (url.Contains("//"))
            {
                url = url.Substring(url.IndexOf("//") + 2);
            }
            if (url.Contains('.'))
            {
                txtBoxOrganization.Text = url.Substring(0, url.IndexOf('.'));
            }
            else
            {
                txtBoxOrganization.Text = url;
            }
        }

        /// <summary>
        /// Preload saved settings
        /// </summary>
        private void LoadSettings()
        {
            txtBoxUrl.Text = (string)Settings.Default[SETTING_CRMURL];
            txtBoxDomain.Text = (string)Settings.Default[SETTING_DOMAIN];
            txtBoxUserId.Text = (string)Settings.Default[SETTING_USERID];
            cbAuthMode.SelectedIndex = (byte)Settings.Default[SETTING_AUTHMODE];
            cbUtility.SelectedIndex = (byte)Settings.Default[SETTING_UTILITY];

            // we set this last so that the OnChange events have no chance to change it
            txtBoxOrganization.Text = (string)Settings.Default[SETTING_CRMORG];
        }

        /// <summary>
        /// Save settings
        /// </summary>
        private void SaveSettings()
        {
            Settings.Default[SETTING_CRMURL] = txtBoxUrl.Text;
            Settings.Default[SETTING_CRMORG] = txtBoxOrganization.Text;
            Settings.Default[SETTING_DOMAIN] = txtBoxDomain.Text;
            Settings.Default[SETTING_USERID] = txtBoxUserId.Text;
            Settings.Default[SETTING_AUTHMODE] = (byte)cbAuthMode.SelectedIndex;
            Settings.Default[SETTING_UTILITY] = (byte)cbUtility.SelectedIndex;

            Settings.Default.Save();
        }

        #endregion

        #region Events

        private void FormLogin_Load(object sender, EventArgs e)
        {
            // form title
            this.Text = this.AssemblyTitle + " v" + AssemblyVersion;

            LoadSettings();
            EnableControls();
            this.ActiveControl = txtBoxPassword;
        }

        private void ExitRequest(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                btnLogin.Enabled = false;
                string url = txtBoxUrl.Text;

                switch (cbAuthMode.SelectedIndex)
                {
                    case 0:
                        // Active Directory
                        this._helper = HelperLogin.LoginIntranet(ref url, txtBoxOrganization.Text, txtBoxDomain.Text,
                            txtBoxUserId.Text, txtBoxPassword.Text);
                        break;

                    case 1:
                        // IFD
                        this._helper = HelperLogin.LoginInternet(ref url, txtBoxOrganization.Text, txtBoxDomain.Text,
                            txtBoxUserId.Text, txtBoxPassword.Text);
                        break;

                    case 2:
                        // CRM Online
                        this._helper = HelperLogin.LoginLive(txtBoxOrganization.Text, txtBoxDomain.Text,
                            txtBoxUserId.Text, txtBoxPassword.Text);
                        break;
                }

                if (_helper != null)
                {
                    // launch utility
                    txtBoxUrl.Text = url;
                    SaveSettings();
                    EnableControls();
                    switch (cbUtility.SelectedIndex)
                    {
                        case 0:
                            FormCompareRoles rolesForm = new FormCompareRoles(_helper.SvcHandle);
                            _utilityForm = rolesForm;
                            rolesForm.Show(this);
                            break;

                        case 1:
                            FormAssignRoles assignForm = new FormAssignRoles(_helper.SvcHandle);
                            _utilityForm = assignForm;
                            assignForm.Show(this);
                            break;

                        case 2:
                            FormManageViews viewsForm = new FormManageViews(_helper.SvcHandle);
                            _utilityForm = viewsForm;
                            viewsForm.Show(this);
                            break;
                    }
                }
                else
                {
                    EnableControls();
                    if (_utilityForm != null)
                    {
                        _utilityForm.Close();
                        _utilityForm = null;
                    }
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            btnLogout.Enabled = false;
            _helper.Logout();
            _helper = null;
            EnableControls();
            if (_utilityForm != null)
            {
                _utilityForm.ParentClose();
                _utilityForm = null;
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new FormAbout(this).ShowDialog(this);
        }

        private void txtBoxUrl_TextChanged(object sender, EventArgs e)
        {
            if (cbAuthMode.SelectedIndex == 1)
            {
                SetOrganization();
            }
        }

        private void cbAuthMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAuthMode.SelectedIndex == 1)
            {
                SetOrganization();
            }
            EnableControls();
        }

        #endregion

    }
}
